# from lib2to3.fixes.fix_input import context
# from os.path import exists
#
# from django.core.exceptions import ValidationError
# from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# from django.core.validators import RegexValidator
# from django.http import HttpResponse
# from django.shortcuts import render, redirect
# from django.template.defaultfilters import title
# from django.utils import timezone
# from django.utils.safestring import mark_safe
#
# from tools import models
# from tools.models.models import Department, UserInfo
# from tools.utils.PageData import PageData
# from tools.utils.Pagination import Pagination
# from tools.utils.Pagination2 import Pagination2
#
# '''
# # Create your views here.
# def index(request):
#     return HttpResponse('欢迎使用！')
#
# # 会按照APP注册顺序找HTML文件
# def user_list(request):
#     return render(request, 'user_list.html')
#
# def user_add(request):
#     return render(request, 'user_add.html')
#
# def tpl(request):
#     name = '张三'
#     roles = ['管理员','CEO','张三']
#     user_info = {'name':'李四','salary':'800', 'role':'CEO'}
#     user_list = [
#         {'name': 'zhangsan', 'salary': '800', 'role': 'CEO'},
#         {'name': 'lisi', 'salary': '900', 'role': 'CFO'},
#         {'name': 'wangwu', 'salary': '1000', 'role': '管理员'},
#     ]
#     return render(request, 'tpl.html', {'n1': name, 'n2': roles, 'n3': user_info, 'n4': user_list} )
#
#
# def news(req):
#     # 定义一条新闻（字典或列表） 或 数据库 网络请求去联通新闻
#     # 地址：
#     # 第三方模块;requests (pip install requests)
#     import requests
#     res = requests.get('https://www.chinaunicom.com.cn/43/menu01/1/column01?pageNo=1&pageSize=10')
#     # data_list = res.json(res)
#     print(res)
#     return render(req, 'news.html')
#
#
# def orm(req):
#     # ########## 1.新建 ##########
#     Department.objects.create(title="销售部")
#     Department.objects.create(title="IT部")
#     Department.objects.create(title="制造部")
#     UserInfo.objects.create(name="zhangsan", password="123456", age=30, account='123',creatime=timezone.now(),depart_id=4)
#     UserInfo.objects.create(name="lisi", password="654321", age=20, account='456',creatime=timezone.now(),depart_id=5)
#     UserInfo.objects.create(name="wangmazi", password="415263", age=25, account='789',creatime=timezone.now(),depart_id=6)
#     UserInfo.objects.create(name="二狗", password="415263")
#
#     # ########## 2.删除 ##########
#     UserInfo.objects.filter(id=5).delete()
#     Department.objects.all().delete()
#
#     # ########## 3.查询 ##########
#     # 3.1 获取符合条件的所有数据
#     # data_list = [行对象,行对象,行对象,……]，QuerySet类型
#     data_list = UserInfo.objects.all()
#     print(data_list)
#     for obj in data_list:
#         print(obj.id, obj.name, obj.password, obj.age)
#
#     # data_list = [行对象,]
#     data_list = UserInfo.objects.filter(id=1)
#     print(data_list)
#
#     # 获取第一条数据（对象）
#     row_obj = UserInfo.objects.filter(id=1).first()
#     print(row_obj.id, row_obj.name, row_obj.password, row_obj.age)
#
#     # ########## 3.更新 ##########
#     UserInfo.objects.all().update(password='999999')
#     UserInfo.objects.filter(name='zhangsan').update(password='888888')
#
#     return HttpResponse('成功！')
#
#
# def info_list(request):
#     # 1.获取数据库中所有用户信息
#     # [对象，对象，对象]
#     data_list = UserInfo.objects.all()
#     print(data_list)
#
#     # 2.渲染，返回给用户
#     return render(request, "info_list.html", {"data_list": data_list})
#
# def info_add(request):
#     if request.method == "GET":
#         return render(request, 'info_add.html')
#
#     # 获取用户提交的数据
#     testuser = request.POST.get("testuser")
#     pwd = request.POST.get("pwd")
#     age = request.POST.get("age")
#
#     # 添加到数据库
#     UserInfo.objects.create(name=testuser, password=pwd, age=age)
#
#     # return HttpResponse("添加成功！")
#     # 自动跳转
#     return redirect("/info/list/")
# '''
# # def orm(req):
# #     UserInfo.objects.create(name="zhangsan", password="123456", age=30, account='123',creatime=timezone.now(),depart_id=4)
# #     UserInfo.objects.create(name="lisi", password="654321", age=20, account='456',creatime=timezone.now(),depart_id=5)
# #     UserInfo.objects.create(name="wangmazi", password="415263", age=25, account='789',creatime=timezone.now(),depart_id=6)
# #     return HttpResponse("添加成功！")
#
#
# def depart_list(request):
#     """ 部门列表 """
#     # # 去数据库获取所有的部门列表
#     # # [对象，对象，对象]
#     # querySet = models.Department.objects.all()
#     #
#     # return render(request, "depart_list.html", {"querySet": querySet})
#
#     # 去数据库中获取所有的部门名称
#     queryset = models.Department.objects.all()
#     page_object = Pagination(request, queryset, page_size=10)  # 每页显示几条（page_size=2）
#     context = {
#         "querySet": page_object.page_queryset,
#         "page_string": page_object.html(),
#     }
#     # print(queryset)
#     return render(request, "testpretty/depart_list.html", context)
#
#
# def depart_add(request):
#     """ 添加部门 """
#     if request.method == "GET":
#         return render(request, "testpretty/depart_add.html")
#
#     # 获取用户POST请求提交过来的数据（title输入为空，先不考虑，后续有组件判断）
#     title = request.POST.get("title")
#
#     # 保存到数据库
#     models.Department.objects.create(title=title)
#
#     # 重定向回列表页面
#     return redirect("/testdepart/list/")
#
#
# def depart_delete(request):
#     """ 删除部门 """
#     # 获取ID http://localhost:8000/depart/delete/?nid=1
#     nid = request.GET.get("nid")
#     # 删除
#     models.Department.objects.filter(id=nid).delete()
#
#     # 重定向回列表页面
#     return redirect("/testdepart/list/")
#
#
# # http://localhost:8000/depart/10/edit/
# # http://localhost:8000/depart/2/edit/
# # http://localhost:8000/depart/4/edit/
# def depart_edit(request, nid):
#     """ 修改部门 """
#     if request.method == "GET":
#         # 根据nid获取部门数据
#         row_object = models.Department.objects.filter(id=nid).first()
#         # print(row_object.id, row_object.title)
#
#         return render(request, "testpretty/depart_edit.html", {"row_object": row_object})
#
#     # 获取用户提交的标题
#     title = request.POST.get("title")
#
#     # 根据ID找到数据库中的数据并进行更新
#     models.Department.objects.filter(id=nid).update(title=title)
#
#     # 重定向回部门列表
#     return redirect("/testdepart/list/")
#
#
# def user_list(request):
#     """ 用户管理 """
#     # 获取所有用户列表[obj, obj, obj]
#     querySet = models.UserInfo.objects.all()
#     """
#     for obj in queryset:
#         print(obj.id, obj.name, obj.account, obj.creatime.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display(), obj.depart_id)
#         print(obj.name, obj.depart_id)
#         # obj.depart_id  # 获取数据库中存储的那个字段值
#         # obj.testdepart.title  # 根据id自动去关联的表中获取哪一行数据depart对象
#     """
#     return render(request, "testuser/user_list.html", {"querySet": querySet})
#
#
# def user_add(request):
#     """ 添加用户 """
#     if request.method == "GET":
#         context = {
#             'gender_choice': models.UserInfo.gender_choice,
#             'depart_list': models.Department.objects.all()
#         }
#         return render(request, "testuser/user_add.html", context)
#
#     # 获取用户提交的数据
#     user = request.POST.get("testuser")
#     pwd = request.POST.get("pwd")
#     age = request.POST.get("age")
#     ac = request.POST.get("ac")
#     ctime = request.POST.get("ctime")
#     gender = request.POST.get("gd")
#     depart_id = request.POST.get("dp")
#
#     # 添加到数据库中
#     models.UserInfo.objects.create(name=user, password=pwd, age=age, account=ac,
#                                    creatime=ctime, gender=gender, depart_id=depart_id)
#
#     # 返回到用户列表页面
#     return redirect("/testuser/list/")
#
#
# # ######################## ModelForm 示例 ########################
# from django import forms
#
# class UserModelForm(forms.ModelForm):
#
#     # 添加一个最小长度校验
#     name = forms.CharField(
#         min_length=3,
#         label="用户名"
#
#     )
#     # password = forms.CharField(validators=正则表达式, label="密码")
#
#     class Meta:
#         model = models.UserInfo
#         fields = ["name", "password", "age", "account", "creatime", "gender", "testdepart"]
#         # widgets = {
#         #     "name": forms.TextInput(attrs={"class": "form-control"}),
#         #     "password": forms.PasswordInput(attrs={"class": "form-control"})
#         # }
#
#     # 添加bootstrap样式
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#
#         # 循环找到所有的字段插件，给所有的插件添加"class: form-control"属性
#         # print(type(self.fields))  # 应该是 <class 'dict'>
#         # print(self.fields)  # 检查内容
#         for name,field in self.fields.items():
#         # for name, field in dict(self.fields).items():
#             print(name,field)
#             field.widget.attrs = {"class": "form-control"}
#
# def user_model_form_add(request):
#     """ 添加用户 ModelForm版本 """
#     if request.method == "GET":
#         form = UserModelForm()
#         return render(request, "testuser/user_model_form_add.html", {"form": form})
#
#     # 用post提交数据，数据校验
#     form = UserModelForm(data=request.POST)
#     if form.is_valid():
#         # 如果数据合法，保存到数据库
#         # {'name': '程青松', 'password': '789', 'age': 88, 'account': Decimal('88888'), 'gender': 1, 'testdepart': <Department: IT测试部>}
#         # print(form.cleaned_data)
#         # models.UserInfo.objects.create(...)
#         form.save()
#         return redirect("/testuser/list/")
#
#     # 校验失败（在页面上显示错误信息）
#     return render(request, "testuser/user_model_form_add.html", {"form": form})
#
#
# def user_edit(request, nid):
#     """ 修改用户 ModelForm版本 """
#     row_object = models.UserInfo.objects.filter(id=nid).first()
#
#     if request.method == "GET":
#         # 根据ID去数据库获取要编辑的那一行数据（对象）
#         form = UserModelForm(instance=row_object)
#         return render(request, "testuser/user_edit.html", {"form": form})
#
#     form = UserModelForm(data=request.POST, instance=row_object)
#     if form.is_valid():
#         # 默认保存的是用户输入的数据，如果想在用户输入以外增加一些值
#         # form.instance.字段名 = 值
#         form.save()
#         return redirect("/testuser/list/")
#     return render(request, "testuser/user_edit.html", {"form": form})
#
#
# def user_delete(request, nid):
#     """ 删除用户 """
#     models.UserInfo.objects.filter(id=nid).delete()
#     return redirect("/testuser/list/")
#
#
#
# # 靓号管理
# def prettynum_list(request):
#     """ 靓号管理 """
#     # # 插入300条数据
#     # for i in range(300):
#     #     models.PrettyNum.objects.create(mobile='18188888888', price=10, level=1, status=1)
#
#     data_dict = {}  # 创建一个空字典用于存储查询条件
#     search_data = request.GET.get("q", "")  # 从URL的GET参数中获取搜索关键词，http://yourdomain.com/prettynum/?q=138
#     if search_data:  # 如果搜索关键词存在
#         data_dict["mobile__contains"] = search_data  # 构建查询条件
#
#     # 1.根据用户想要访问的页码，计算出起止位置
#     page = int(request.GET.get("page", 1))
#     page_size = 10  # 每页显示10条数据
#     start = (page - 1) * page_size
#     end = page * page_size
#
#     # 获取所有数据并按level降序排列
#     # queryset = models.PrettyNum.objects.all().order_by("-level")
#     querySet = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
#
#     # 数据总条数
#     total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
#
#     # 总页码
#     total_page_count, div = divmod(total_count, page_size)
#     if div:
#         total_page_count += 1
#
#     # 计算出，显示当前页面的前5页、后5页
#     plus = 5
#     start_page = page - plus
#     end_page = page + plus + 1
#
#     # 页码
#     page_str_list = []
#     for i in range(start_page, end_page):
#         if i == page:
#             ele = '<li class="activate"><a herf="?page={}">{}</a></li>'.format(i, i)
#         else:
#             ele = '<li><a herf="?page={}">{}</a></li>'.format(i, i)
#         page_str_list.append(ele)
#
#     # 尾页
#     page_str_list.append('<li><a herf="?page={}">尾页</a></li>'.format(total_page_count))
#
#     page_string = mark_safe("".join(page_str_list))
#
#     # querySet = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
#     return render(request, "testpretty/prettynum_list.html", {"querySet": querySet, "page_string": page_string})
#
#
# def pretty_list(request):
#     # pretty_list = models.PrettyNum.objects.all()
#     # 搜索信息
#     dict_data = {}
#     # 获取搜素框里的内容, 就是获取网址里面的search参数的值
#     value = request.GET.get('search')
#     if value:
#         # 在表格中搜素包含输入框当中的数据, 这里搜素的是手机号, key为mobile__contains
#         dict_data["mobile__contains"] = value
#     pretty_list = models.PrettyNum.objects.filter(**dict_data)
#     page_object = PageData(request, pretty_list)
#     # 调用我们自己写的page_html函数, 在PageData类当中。
#     page_string = page_object.page_html()
#     # 不能忘记将page_string传给前端。
#     return render(request, "testpretty/prettynum_list.html",
#                   {"querySet": page_object.page_queryset, "page_string": page_string})
#
# # 新增靓号
# class PrettynumForm(forms.ModelForm):
#
#     # 验证：方式一
#     mobile = forms.CharField(
#         label="手机号",
#         # validators=[RegexValidator(r'^159[0-9]+$', '数字必须以159开头'),],
#         # validators=[RegexValidator(r'^1\d{10}$', '手机号格式错误'),],
#         validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'),],
#     )
#     # mobile = forms.CharField(
#     #     label=("手机号"),
#     #     max_length=11,
#     #     min_length=11,
#     #     validators=[
#     #         RegexValidator(
#     #             r'^1[3456789]\d{9}$',  # 更精确的运营商号段
#     #             message=("请输入正确的11位手机号")
#     #         )
#     #     ],
#     #     widget=forms.TextInput(attrs={
#     #         'placeholder': ('请输入手机号'),
#     #         'pattern': '1[3456789]\\d{9}',  # HTML5 前端验证
#     #         'title': ('请输入11位手机号')
#     #     })
#     # )
#
#     class Meta:
#         model = models.PrettyNum
#         fields = ["mobile", "price", "level", "status"]
#         # fields = "__all__"      # 全部字段
#         # exclude = ['level']   # 排除某个字段
#         # widgets = {
#         #     "mobile": forms.TextInput(attrs={"class": "form-control"}),
#         #     "price": forms.PasswordInput(attrs={"class": "form-control"})
#         # }
#
#     # 添加bootstrap样式
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#
#         # 循环找到所有的字段插件，给所有的插件添加"class: form-control"属性
#         # print(type(self.fields))  # 应该是 <class 'dict'>
#         # print(self.fields)  # 检查内容
#         for name,field in self.fields.items():
#         # for name, field in dict(self.fields).items():
#             print(name,field)
#             field.widget.attrs = {"class": "form-control"}
#
#     # 验证：方式二，钩子方法
#     def clean_mobile(self):
#
#         # 当前编辑的哪一行的ID
#         print(self.instance.pk)
#
#         txt_mobile = self.cleaned_data["mobile"]  # 获取用户输入/传入的数据
#
#         # exclude(id=self.instance.pk) 排除自己
#         exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
#         if exists:
#             raise ValidationError("手机号已存在！")
#
#         # if len(txt_mobile) != 11:
#         #     # 验证不通过
#         #     raise ValidationError("格式错误")
#         # 验证通过
#         return txt_mobile
#
# def prettynum_add(request):
#     """ 添加靓号 ModelForm版本 """
#     if request.method == "GET":
#         form = PrettynumForm()
#         return render(request, "testpretty/prettynum_add.html", {"form": form})
#
#     # 用post提交数据，数据校验
#     form = PrettynumForm(data=request.POST)
#     if form.is_valid():
#         # 如果数据合法，保存到数据库
#         # {'name': '程青松', 'password': '789', 'age': 88, 'account': Decimal('88888'), 'gender': 1, 'testdepart': <Department: IT测试部>}
#         print(form.cleaned_data)
#         # models.UserInfo.objects.create(...)
#         form.save()
#         return redirect("/prettynum/list/")
#
#     # 校验失败（在页面上显示错误信息）
#     return render(request, "testpretty/prettynum_add.html", {"form": form})
#
#
# def prettynum_edit(request, nid):
#     """ 修改靓号 """
#     row_object = models.PrettyNum.objects.filter(id=nid).first()
#
#     if request.method == "GET":
#         # 根据ID去数据库获取要编辑的那一行数据（对象）
#         form = PrettynumForm(instance=row_object)
#         return render(request, "testpretty/prettynum_edit.html", {"form": form})
#
#     form = PrettynumForm(data=request.POST, instance=row_object)
#     if form.is_valid():
#         # 默认保存的是用户输入的数据，如果想在用户输入以外增加一些值
#         # form.instance.字段名 = 值
#         form.save()
#         return redirect("/prettynum/list/")
#     return render(request, "testpretty/prettynum_edit.html", {"form": form})
#
#
# def prettynum_delete(request, nid):
#     """ 删除靓号 """
#     models.PrettyNum.objects.filter(id=nid).delete()
#     return redirect("/prettynum/list/")
#
#
#
#
#
